<template>
	<view class="common-container">
		<fui-nav-bar title="登录/注册" isFixed isOccupy></fui-nav-bar>
		<view class="u-flex u-row-center u-p-t-80 u-p-b-80">
			<sn-image url="/static/common/logo.png" ></sn-image>
		</view>
		<view class="u-p-l-70 u-p-r-70">
			<fui-input placeholder="请输入手机号" v-model="phoneNumber">
				<template v-slot:left>
					<sn-image url="/static/login/phoneIcon.png"  class="u-m-r-20" :width="42" :height="48" ></sn-image>
				</template>
			</fui-input>
			<fui-input  placeholder="请输入验证码" v-model="code" :padding="['28rpx',0,'28rpx','32rpx',]" v-if="!loginByPassword">
				<template v-slot:left>
					<sn-image url="/static/login/codeIcon.png"  class="u-m-r-20" :width="42" :height="48"></sn-image>
				</template>
				<fui-countdown-verify ref="fui_cdv" :text="'获取验证码'" :color="'#333'" :borderColor="'transparent'" @send="sendCode"></fui-countdown-verify>
			</fui-input>
			<fui-input  placeholder="请输入密码"  v-model="password" :password="passwordShow" :padding="['28rpx',0,'28rpx','32rpx',]" v-if="loginByPassword">
				<template v-slot:left>
					<sn-image url="/static/login/passwordIcon.png"  class="u-m-r-20" :width="42" :height="48"></sn-image>
				</template>
				<fui-icon :name="passwordShow?'invisible':'visible'" color="#B2B2B2" :size="50" @click="passwordChange"></fui-icon>
			</fui-input>
			<view class="u-flex u-m-t-70 u-m-b-20 u-row-center">
				<fui-checkbox :checked="isAgree" color="#ffbb1a" scaleRatio=".7" @change="isAgreeChange"></fui-checkbox>
				<text @click="isAgree = !isAgree" class="u-m-l-10 u-font-22">
					<text :style="{color:' #999999', fontSize: 22 + 'rpx'}">已阅读并且同意</text>
					<text :style="{color: '#ffbb1a', fontSize: 22 + 'rpx'}" @click.stop="toPage('00000000-0000-0000-0000-000000000002', '用户协议')">《用户协议》</text>
					<text :style="{color: '#ffbb1a', fontSize: 22 + 'rpx'}" @click.stop="toPage('00000000-0000-0000-0000-000000000004', '隐私条款')">《隐私条款》</text>
				</text>
			</view>
			<fui-button @tap="loginFn()">登 录/注 册</fui-button>
			<!-- 其他登录方式 -->
			<view class="u-text-right u-m-t-30" @click="switchLoginMethod()">
				<text class="u-font-grey u-font-28" >{{loginByPassword?'验证码登录':'密码登录'}}</text>
			</view>
			<fui-loading :isFixed="true" v-if="loading" isMask></fui-loading>
		</view>
	</view>
</template>

<script setup>
	import { ref,reactive,getCurrentInstance } from 'vue';
	import { sendSms,requestToken } from '@/config/idsApi.js'
	import SnImage from '@/components/sn-image.vue';
	import {useUserStore} from '@/store/user.js';
	import {useShopStore} from '@/store/shop.js'
	const phoneNumber = ref('');
	const code = ref('');
	const password = ref('');
	const fui_cdv = ref();
	const isAgree = ref(false);
	const loading = ref(false);
	const loginByPassword = ref(false);
	const passwordShow = ref(true);
	const {proxy} = getCurrentInstance();
	const userStore = useUserStore();
	const shopStore  = useShopStore();
	function isAgreeChange(val){
		isAgree.value = val.checked;
	}
	function passwordChange(){
		passwordShow.value = !passwordShow.value;
	}
	// 跳转协议 
	function toPage(id, name) {
		proxy.$mRouter.push({ route: '/pages/mine/shezhi/lawDetail?id='+id+'&name='+name })
	};
	// 切换登录方式
	function switchLoginMethod(){
		loginByPassword.value = !loginByPassword.value;
	};
 	// 发送验证码
	async function sendCode(){
		if(!uni.$fui.isMobile(phoneNumber.value)){
			fui_cdv.value.reset()
			return uni.$fui.toast('请输入正确的手机号');
		}
		try {
			const res = await sendSms({ phoneNumber: phoneNumber.value});
			console.log(res);
			if (res.code === 200) {
				fui_cdv.value.success();
			} else {
				fui_cdv.value.reset()
				uni.$fui.toast(res.erroMessage);
			}
		} catch (error) {
			fui_cdv.value.reset()
			uni.$fui.toast('异常抛出');
		}
	}
	async function loginFn(){
		loading.value = true;
		if(!uni.$fui.isMobile(phoneNumber.value)){
			loading.value = false;
			return uni.$fui.toast('请输入正确的手机号');
		};
		// 发送请求
		const params = {
			client_id: 'client_app',
			client_secret: '511536EF-F270-4058-80CA-1C89C192F69A',
			scope: 'scope_app openid profile',
			grant_type: 'password',
			username: phoneNumber.value,
		}
		if(loginByPassword.value){
			if(!password.value){
				loading.value = false;
				return uni.$fui.toast('请输入密码');
			}
			params.password = password.value;
			params.policy_name = 'password'
		}else{
			if(!code.value){
				loading.value = false;
				return uni.$fui.toast('请输入验证码');
			}
			params.smsCode = code.value;
			params.policy_name = 'sms'
		}
		if(!isAgree.value){
			loading.value = false;
			return uni.$fui.toast('请先阅读并同意用户协议与隐私政策');
		};
		try {
	
			// 判断手机号是否需要绑定 （后台录入账户与真实用户需要做一个绑定） 缓存手机号，需要在valid 页面中使用
			uni.setStorageSync('validPhone', phoneNumber);
			// 请求ids token
			const token = await requestToken(params)
			if (!token) return
			uni.setStorageSync('access_token', token)
			// 获取成功之后 根据token获取用户信息 (如果手机号需要绑定的情况下，后台返回1001.在接口拦截中跳转 valid 绑定手机号页面)
			
			const info = await proxy.$http.post('api/User/LoginOrRegister');
			loading.value = false;
			// 获取用户信息成功之后（证明手机号已有关联具体用户）删除缓存手机号
			uni.removeStorageSync('validPhone')
			info.access_token = token;
			userStore.login(info) //保存用户信息到pina仓库中
			// 判断用户是否已经实名认证
			if(!userStore.isAuthRealName){
				proxy.$mRouter.redirectTo({route:'/pages/login/userAuth'});
			}else{
				const res = await proxy.$newHttp.get('api/User/GetShopsByUser' );
				if(res.code === 200){
					if(res.data.length!=0){
						userStore.checkStatus = 3;
						shopStore.login(res.data);
					}else{
						userStore.checkStatus = 2;
					}
				}else{
					userStore.checkStatus = 3;
					uni.$fui.toast('获取店铺列表失败，请在首页下来刷新重新获取');
				}
				await proxy.$mHelper.getTabbar();
				setTimeout(function(){
					uni.reLaunch({
						url: '/pages/index/index',
					})
				},1000)
			}
		} catch (error) {
			//TODO handle the exception
			loading.value = false;
		}
	}
</script>

<style>
</style>